/*
 * jQuery UI WindowedDialog 0.5.2
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

    $.widget("ui.windowedDialog", {

        _init: function() {
            var self = this,
			options = this.options;

            this._dialog = null;
            $.ui.windowedDialog.instances[options.frameName] = this;
            if (this.length > 1 && this.element[0] != window) {
                $(this.element).bind('click.windowedDialog', function(event) { self.open(); });
            }
            (options.autoOpen && this.open());
        },

        close: function(event) {
            if (!this.isOpen()) { return; }
            if (false === this._trigger('beforeClose', event, this)) {
                return;
            }

            this._dialogClosed(event);
        },

        _dialogClosed: function(event) {
            (this.overlay && this.overlay.destroy());
            (this.isOpen() && this._dialog.close());
            (this.dialogResult() != undefined && this._trigger('result', event, this));
            this._trigger('close', event, this);
        },

        dialogResult: function(result, force) {
            if (result === undefined && !force) {
                return this.element.data('dialogResult');
            }
            this.element.data('dialogResult', result);
            return this;
        },

        destroy: function() {
            (this.overlay && this.overlay.destroy());
            this.close();
            jQuery(this.element[0]).unbind('.windowedDialog');
        },

        focus: function() {
            if (this.isOpen()) {
                this._dialog.focus();
            }
        },

        isOpen: function() {
            return !!this._dialog && !this._dialog.closed;
        },

        open: function() {
            if (this.isOpen()) { return; }

            var self = this,
			options = this.options;

            this.overlay = options.modal ? new $.ui.windowedDialog.overlay(this) : null;

            var windowOptions = '';
            if (options.centerScreen) {
                windowOptions += 'left=' + parseInt((screen.availWidth - options.width) / 2)
							+ ',top=' + parseInt((screen.availHeight - options.height) / 2);
            }
            else {
                if (options.left) {
                    windowOptions += 'left=' + options.left;
                }
                else {
                    windowOptions += 'left=' + parseInt(($(window).width() - options.width) / 2);
                }
                if (options.top) {
                    windowOptions += ',top=' + options.top;
                }
                else {
                    windowOptions += ',top=' + parseInt(($(window).height() - options.height) / 2);
                }
            }
            if (options.dependant || options.modal) {
                //			if ($.browser.mozilla) {
                //				windowOptions += ',dependant=yes';
                //			}
                //			else {
                $(window).bind('unload.windowedDialog', function(event) { self.close(); });
                //			}
            }
            windowOptions += ',height=' + options.height;
            if (options.location) {
                windowOptions += ',location=yes';
            }
            if (options.menubar) {
                windowOptions += ',menubar=yes';
            }
            if (options.resizable) {
                windowOptions += ',resizable=yes';
            }
            if (options.scrollbars) {
                windowOptions += ',scrollbars=yes';
            }
            if (options.status) {
                windowOptions += ',status=yes';
            }
            if (options.toolbar) {
                windowOptions += ',toolbar=yes';
            }
            windowOptions += ',width=' + options.width;

            this._dialog = window.open(options.url, options.frameName, windowOptions);
            this._trigger('open', null, this);
        }
    });

    $.fn.windowedDialog = function(options) {
        // handle initialization and non-getter methods
        return this.each(function() {
            var instance = $.ui.windowedDialog.instances[options.frameName] || new $.ui.windowedDialog(options, this);

            // constructor
            instance._init();
        });
    };

    $.extend($.ui.windowedDialog, {
        version: "0.5.1",
        defaults: {
            autoOpen: false,
            centerScreen: false,
            dependant: false,
            frameName: 'dialog',
            height: 300,
            left: null,
            location: false,
            menubar: false,
            modal: false,
            resizable: false,
            scrollbars: false,
            status: false,
            theme: null,
            toolbar: false,
            top: null,
            url: 'about:blank',
            width: 400
        },

        instances: {},

        getter: 'isOpen dialogResult',

        overlay: function(windowedDialog) {
            this.$el = $.ui.windowedDialog.overlay.create(windowedDialog);
        },

        open: function(dialogName, evt) {
            var inst = $.ui.windowedDialog.instances[dialogName];
            if (!!inst) {
                inst.open(evt);
            }
        },

        close: function(dialogName, evt) {
            var inst = $.ui.windowedDialog.instances[dialogName];
            if (!!inst) {
                inst.close(evt);
            }
        },

        destroy: function(dialogName, evt) {
            var inst = $.ui.windowedDialog.instances[dialogName];
            if (!!inst) {
                inst.destroy(evt);
            }
        },

        notifyUnload: function(dialogName, evt) {
            setTimeout(function() {
                    var inst = $.ui.windowedDialog.instances[dialogName];
                    if (!!inst && !inst.isOpen()) {
                        inst.dialogResult(undefined, true);
                        inst._dialogClosed(evt);
                    }
                }, 100);
        },

        setDialogResult: function(dialogName, result) {
            var inst = $.ui.windowedDialog.instances[dialogName];
            if (!!inst) {
                inst.dialogResult(result);
                inst.close();
            }
        },

        cancelDialog: function(dialogName) {
            var inst = $.ui.windowedDialog.instances[dialogName];
            if (!!inst) {
                inst.dialogResult(undefined, true);
                inst._dialogClosed();
            }
        }
    });

    $.extend($.ui.windowedDialog.overlay, {
        instances: [],
        events: $.map('focus,mousedown,mouseup,keydown,keypress,click'.split(','),
		function(event) { return event + '.windowedDialog-overlay'; }).join(' '),
        create: function(windowedDialog) {
            if (this.instances.length === 0) {
                // prevent use of anchors and inputs
                // we use a setTimeout in case the overlay is created from an
                // event that we're going to be cancelling (see #2804)
                setTimeout(function() {
                    $(document).bind($.ui.windowedDialog.overlay.events, function(event) {
                        if (!windowedDialog.isOpen()) {
                            windowedDialog._dialogClosed(event);
                        }
                        else {
                            windowedDialog.focus();
                            return false;
                        }
                    });
                    $(window).bind('focus.windowedDialog-overlay', function(event) {
                        if (!windowedDialog.isOpen()) {
                            windowedDialog._dialogClosed(event);
                        }
                        else {
                            windowedDialog.focus();
                            return false;
                        }
                    });
                }, 1);

                // handle window resize
                $(window).bind('resize.windowedDialog-overlay', $.ui.windowedDialog.overlay.resize);
            }

            var $ol = $('<div></div>').addClass('ui-widget-overlay').css({
                width: this.width(),
                height: this.height()
            });
            var $el = (!!windowedDialog.options.theme
					   ? $('<div></div>').addClass(windowedDialog.options.theme).append($ol)
					   : $ol).appendTo(document.body);

            this.instances.push($el);
            return $el;
        },

        destroy: function($el) {
            this.instances.splice($.inArray(this.instances, $el), 1);

            if (this.instances.length === 0) {
                $([document, window]).unbind('.windowedDialog-overlay');
            }

            $el.remove();
        },

        height: function() {
            // handle IE 6
            if ($.browser.msie && $.browser.version < 7) {
                var scrollHeight = Math.max(
				document.documentElement.scrollHeight,
				document.body.scrollHeight
			);
                var offsetHeight = Math.max(
				document.documentElement.offsetHeight,
				document.body.offsetHeight
			);

                if (scrollHeight < offsetHeight) {
                    return $(window).height() + 'px';
                } else {
                    return scrollHeight + 'px';
                }
                // handle "good" browsers
            } else {
                return $(document).height() + 'px';
            }
        },

        width: function() {
            // handle IE 6
            if ($.browser.msie && $.browser.version < 7) {
                var scrollWidth = Math.max(
				document.documentElement.scrollWidth,
				document.body.scrollWidth
			);
                var offsetWidth = Math.max(
				document.documentElement.offsetWidth,
				document.body.offsetWidth
			);

                if (scrollWidth < offsetWidth) {
                    return $(window).width() + 'px';
                } else {
                    return scrollWidth + 'px';
                }
                // handle "good" browsers
            } else {
                return $(document).width() + 'px';
            }
        },

        resize: function() {
            /* If the dialog is draggable and the user drags it past the
            * right edge of the window, the document becomes wider so we
            * need to stretch the overlay. If the user then drags the
            * dialog back to the left, the document will become narrower,
            * so we need to shrink the overlay to the appropriate size.
            * This is handled by shrinking the overlay before setting it
            * to the full document size.
            */
            var $overlays = $([]);
            $.each($.ui.windowedDialog.overlay.instances, function() {
                $ol = jQuery(this);
                $overlays = $overlays.add($ol.hasClass('ui-widget-overlay') ? this : $ol.children().get(0));
            });

            $overlays.css({
                width: 0,
                height: 0
            }).css({
                width: $.ui.windowedDialog.overlay.width(),
                height: $.ui.windowedDialog.overlay.height()
            });
        }
    });

    $.extend($.ui.windowedDialog.overlay.prototype, {
        destroy: function() {
            $.ui.windowedDialog.overlay.destroy(this.$el);
        }
    });

})(jQuery);
